package model;
import java.util.List;

import com.jfinal.plugin.activerecord.Db;

import enums.MenuType;
import model.base.BaseMenu;

@SuppressWarnings("serial")
public class Menu extends BaseMenu<Menu> {
	public static final Menu dao = new Menu().dao();

	public int getMaxOrderNum(){
    	return Db.queryLong(" SELECT IFNULL(MAX(tm.orderNum),0) FROM t_menu tm WHERE tm.parentId = ? " , getParentId() ).intValue() + 1 ;
    }

	public void setMaxOrderNum(){
    	if (null == getOrderNum()) {
			setOrderNum(getMaxOrderNum());
		}
    }

	public Long CountByParentId(Long parentId){
		return Db.queryLong(" SELECT COUNT(tm.id) FROM t_menu tm WHERE tm.parentId = ?  " , parentId );
	}

	public Menu findFirstByNameAndUrl(String name , String url){
        return this.findFirst(" SELECT tm.* FROM t_menu tm WHERE tm.name = ? AND tm.url = ?  LIMIT 1 " , name , url);
    }

	public boolean isRepeatName(){
		Menu ex = Menu.dao.findFirstByNameAndUrl( getName() , getUrl() );
		return ( null == getId() && null != ex) || (null != ex && !ex.getId().equals(getId()));
	}

	public List<Menu> findByType(Integer type){
        return this.find(" SELECT tm.* FROM t_menu tm WHERE tm.type = ?  ORDER BY tm.orderNum " , type);
    }

	public boolean isLevelOneType(){
        return null != getType() && MenuType.getLevelOne() == getType() ;
    }

	public void setLevelOneType(){
    	setType(MenuType.getLevelOne());
    }

	public boolean isLevelSecType(){
        return null != getType() && MenuType.getLevelSec() == getType() ;
    }

	public void setLevelSecType(){
    	setType(MenuType.getLevelSec());
    }

	public boolean isNotMenuType(){
        return null != getType() && MenuType.getNotMenu() == getType() ;
    }

	public void setNotMenuType(){
    	setType(MenuType.getNotMenu());
    }
}
